import React, { Component } from 'react';
import { Upload, message } from 'antd';
import oss from '@/utils/oss/index';
import styles from './index.less';
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons';

export default class ArticleEdit extends Component {
  state = {
    uploadPicLoading: false,
  };

  // 封面上传部分
  beforeUpload = (file) => {
    const mimeType = ['image/gif', 'image/png', 'image/jpeg', 'image/bmp', 'image/webp'];
    const isJPG = mimeType.includes(file.type);
    if (!isJPG) {
      message.error('您只能上传图片类型为jpg、png、bmp、webp、gif的图片');
    }
    const isLt2M = file.size / 1024 / 1024 < 4;
    if (!isLt2M) {
      message.error('图片大小必须小于4M！');
    }
    return isJPG && isLt2M;
  };

  // 自定义封面上传
  handleCustomRequest = (options) => {
    const { setImg } = this.props;
    this.setState({ uploadPicLoading: true });
    const Name = options.file.name.slice(0, options.file.name.indexOf('.'));
    const ExtName = options.file.name.slice(options.file.name.lastIndexOf('.'));
    oss.ucuxin.uploader(
      {
        options,
        attachmentStr: `{"Path":"","AttachType":1,"Name":'${Name}',"ExtName":'${ExtName}',"ResizeMode":1,"SImgResizeMode":2,"CreateThumb":false}`,
        autoResizeLargeImage: true,
      },
      (res) => {
        if (res.Ret === 0) {
            setImg(res.Data.Url);
        } else {
          message.error('上传失败！');
        }
      },
    );
  };

  render() {
    const { img } = this.props;
    const { uploadPicLoading } = this.state;
    return (
      <div>
        <Upload
          className={styles.avatarUploader}
          name="avatar"
          showUploadList={false}
          beforeUpload={this.beforeUpload}
          customRequest={this.handleCustomRequest}
          accept="image/gif,image/png,image/jpeg,image/bmp,image/webp"
        >
          {img ? (
            <img src={img} alt="" className={styles.avatar} />
          ) : (
            <div className={styles.avatarUploaderTrigger}>
              {uploadPicLoading ? <LoadingOutlined /> : <PlusOutlined />}
              <br />
              {uploadPicLoading ? '正在上传...' : '上传栏目封面'}
            </div>
          )}
        </Upload>
      </div>
    );
  }
}
